package canraid.gui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import canraid.agent.Iagent;
import canraid.agent.implementations.EasyStartAgent;
import canraid.config.Properties;
import canraid.debug.Level;
import canraid.debug.Logger;
import canraid.gen.R;
import canraid.gui.listeners.AgentController;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.LauncherActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

public class EasyStart extends Activity{
	private static AgentController agentController=AgentController.getInstance();
	private static RelativeLayout layoutTasks=null;
	private static EditText textPlate=null;
	private static ImageView imageBtActiving=null;
	private static ImageView imageBtFirstDownloading=null;
	private static ImageView imageNtwRequest=null;
	private static ImageView imageGetTicket=null;
	private static TextSwitcher textIdTicket=null;
	private static ImageView imagePlate=null;
	private static ImageView imageReadyToRemoteInteraction=null;
	private static Button button = null;
	private static Button buttonChat = null;
	private static Drawable imageDot=null;
	private static Drawable imageOk=null;
	private static Drawable imageNot=null;
	private static Drawable imageWait=null;
	private Activity activity=null;
	private static Animation in = null;
	private static Animation out = null;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        activity=this;
        Logger.startLog(this);
        Logger.setLog((Object)this,Level.ASSERT,"onCreate().");
        
        setContentView(canraid.gen.R.layout.easy_start);
        layoutTasks=(RelativeLayout)findViewById(canraid.gen.R.id.layoutListTask);
        textPlate=(EditText)findViewById(canraid.gen.R.id.textPlate);
        imageBtActiving=(ImageView)findViewById(canraid.gen.R.id.imageBtActiving);
        imageBtFirstDownloading=(ImageView)findViewById(canraid.gen.R.id.imageBtFirstDownloading);
        imageNtwRequest=(ImageView)findViewById(canraid.gen.R.id.imageNtwRequest);
        imageGetTicket=(ImageView)findViewById(canraid.gen.R.id.imageGetTicket);
        textIdTicket=(TextSwitcher)findViewById(canraid.gen.R.id.textIdTicket);
        imagePlate=(ImageView)findViewById(canraid.gen.R.id.imagePlate);
        imageReadyToRemoteInteraction=(ImageView)findViewById(canraid.gen.R.id.imageReadyToRemoteInteraction);
        button = (Button) findViewById(canraid.gen.R.id.buttonActionEasyStart);
        buttonChat = (Button) findViewById(canraid.gen.R.id.buttonActionEasyStartChat);
        imageDot = getResources().getDrawable(canraid.gen.R.drawable.dot);
        imageOk = getResources().getDrawable(canraid.gen.R.drawable.checked);
        imageNot = getResources().getDrawable(canraid.gen.R.drawable.failed);
        imageWait = getResources().getDrawable(canraid.gen.R.drawable.waiting);
        in = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
        out = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
        
        agentController.doSettings(this, guiHandler);
        button.setOnClickListener(agentController);
        buttonChat.setOnClickListener(agentController);
        InputFilter[] FilterArray = new InputFilter[2];
        FilterArray[0] = new InputFilter.LengthFilter(7);
        FilterArray[1] = new InputFilter.AllCaps();
        textPlate.setFilters(FilterArray);
        textPlate.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            	String plate=s.toString();
            	Matcher matcherPlate= agentController.patternPlate.matcher(plate);
            	if(!matcherPlate.matches()){
            		imagePlate.setImageDrawable(imageNot);
            		//button.setEnabled(false);
            	}else{
            		imagePlate.setImageDrawable(imageOk);
            		//button.setEnabled(true);
            	}
            }
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {}    
            public void onTextChanged(CharSequence s, int start, int before,int count) {}
         
        });

        textIdTicket.setFactory(
        		new ViewFactory(){
		        	public View makeView() {
		                TextView t = new TextView(activity);
		                return t;
		        	}
        		});
        textIdTicket.setInAnimation(in);
        textIdTicket.setOutAnimation(out);
        layoutTasks.setVisibility(View.INVISIBLE);
    }	
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Logger.setLog((Object)this,Level.ASSERT,"onActivityResult().");	
        agentController.onActivityResult(requestCode, resultCode, data);
    }
	
	public void onDestroy(){
		Logger.setLog((Object)this,Level.ASSERT,"onDestroy().");
		
		agentController.destroy();
		Logger.stopLog();
		super.onDestroy();
		
	}
	
	public final Handler guiHandler = new Handler() {
		
        public void handleMessage(Message msg) {
            
            switch (msg.what) {
            case Iagent.ACTION_EASY_START:
            	
            	if (msg.arg1==0){
            		Logger.setLog(this,Level.ASSERT,"handleMessage(). DOT_ALL");
            		layoutTasks.setVisibility(View.VISIBLE);
            		layoutTasks.startAnimation(in);
            		imageBtActiving.setImageDrawable(imageDot);
                    imageBtFirstDownloading.setImageDrawable(imageDot);
                    imageNtwRequest.setImageDrawable(imageDot);
                    imageGetTicket.setImageDrawable(imageDot);
                    textIdTicket.setText("");
                    imageReadyToRemoteInteraction.setImageDrawable(imageDot);
            	}
            	else if(msg.arg1==canraid.gen.R.id.textIdTicket){
            		String text=(String)msg.obj;
            		textIdTicket.setText(text);
            		Logger.setLog(this,Level.INFO,"handleMessage(). TEXT_ID_TICKET:"+text);
            	}
            	else if(msg.arg1==canraid.gen.R.id.buttonActionEasyStart){
            		String text=getString(msg.arg2);
            		button.setText(text);
            		button.setEnabled(true);
            		Logger.setLog(this,Level.INFO,"handleMessage(). BUTTON_EASYSTART_TEXT:"+text);
            	}
            	else{
	            	try{
	            		ImageView image=(ImageView)findViewById(msg.arg1);
	            		if (msg.arg2==Iagent.ACTION_EASY_START_OK){
	            			image.setImageDrawable(imageOk);
	            			Logger.setLog(this,Level.INFO,"handleMessage(). IMAGE_OK:"+msg.arg1);
	            			if (msg.arg1==canraid.gen.R.id.imageReadyToRemoteInteraction){
	            				//String text=getString(canraid.gen.R.string.button_easy_start_chat);
	                    		//button.setText(text);
	            				button.setEnabled(false);
	                    		buttonChat.setVisibility(View.VISIBLE);
	            				//Logger.setLog(this,Level.INFO,"handleMessage(). BUTTON_EASYSTART_TEXT:"+text);
	            			}
	            		}
	            		else if (msg.arg2==Iagent.ACTION_EASY_START_WAIT){
	            			image.setImageDrawable(imageWait);
	            			String text=getString(canraid.gen.R.string.button_easy_start_abort);
                    		button.setText(text);
                    		button.setEnabled(true);
            				Logger.setLog(this,Level.INFO,"handleMessage(). BUTTON_EASYSTART_TEXT:"+text);
	            		}
	            		else if (msg.arg2==Iagent.ACTION_EASY_START_NOT_OK){
	            			image.setImageDrawable(imageNot);
	            			String text=getString(canraid.gen.R.string.button_easy_start_restart);
                    		button.setText(text);
                    		button.setEnabled(true);
                    		textPlate.setEnabled(true);
            				Logger.setLog(this,Level.INFO,"handleMessage(). BUTTON_EASYSTART_TEXT:"+text);
	            		}
	            	}catch(Exception e){}
            	}
            	break;
            
            case Iagent.ACTION_EASY_START_ERROR:
            	Logger.setLog(this,Level.INFO,"handleMessage(). ALERT:"+Properties.TEXT_EASY_START[msg.arg1]);
            	Toast.makeText(activity, Properties.TEXT_EASY_START[msg.arg1], Toast.LENGTH_LONG).show();
            break;
            	
            default:
            	Logger.setLog(this,Level.INFO,"handleMessage()."+msg.what+": Type not implemented.");
                break;
            }
        }
	};
	
    public boolean onCreateOptionsMenu(Menu menu) {
    	Logger.setLog((Object)this,Level.ASSERT,"onCreateOptionsMenu().");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_canraid, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
    	Logger.setLog((Object)this,Level.ASSERT,"onOptionsItemSelected().");
        return agentController.onOptionsItemSelected(item);
    }

}
